package com.server.http.controller;

import com.server.dao.AlarmDao;
import com.server.dao.AlarmMessageDao;
import com.server.dao.MobileAppDao;
import com.server.dao.UnitDao;
import com.server.pojo.Alarm;
import com.server.pojo.AlarmMessage;
import com.server.pojo.MobileApp;
import com.server.pojo.Unit;
import com.server.http.anYuan.AnYuanServer;
import com.server.http.service.MobileAppService;
import com.server.http.service.UnitService;
import com.server.libs.ret.RE;
import com.server.libs.ret.R;
import com.server.http.service.AlarmService;
import com.server.libs.Save;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping(value = "/alarm")
@Slf4j
@Transactional
public class AlarmController {
    @Autowired
    AlarmDao alarmDao;
    @Autowired
    UnitDao unitDao;

    @Autowired
    MobileAppService mobileAppService;

    @Autowired
    MobileAppDao mobileAppDao;

    @Autowired
    AlarmService alarmService;

    @Autowired
    AlarmMessageDao alarmMessageDao;

    @Autowired
    UnitService unitService;

    @Autowired
    Save save;

    @RequestMapping(value = "/new", method = {RequestMethod.GET, RequestMethod.POST})
    public R<Alarm> add(@RequestBody Alarm alarm) {

        Unit unit = unitDao.findById(alarm.getUnit().getId()).orElse(null);
        alarm.setUnit(unit);
        alarmDao.save(alarm);
        return new R<Alarm>("ok").setData(alarmService.push(alarm));
    }

    @RequestMapping(value = "/add", method = {RequestMethod.POST})
    @Transactional
    public R<String> addMessage(@RequestHeader String authorization,
                                @RequestParam(required = false) String title,
                                @RequestParam(required = false) String content,
                                @RequestParam(required = false) List<MultipartFile> files) {  //参数名需与前端文件标签名一样
        MobileApp mobileApp = mobileAppService.checkLogin(authorization);
        List<String> paths = new ArrayList<>();

        Map<String,Object> data = new HashMap<>();
        data.put("com",121);
        data.put("titlestr",title);
        data.put("textstr",content);
        data.put("jingdu",mobileApp.getLongitude());
        data.put("weidu",mobileApp.getLatitude());
        data.put("admin",mobileApp.getAccount());

        try {
            if(files != null) {
                int i = 0;
                for (MultipartFile file : files) {
                    i++;
                    String path = "alarm/";
                    path += mobileApp.getAccount() + "/";
                    path += UUID.randomUUID().toString().replace("-","")+"/";
                    path += i + "_" + file.getOriginalFilename();
                    paths.add(save.toUrl(file, path));
                }
            }
            data.put("fileurl",String.join(";",paths));

        }catch (Exception e){
            throw new RE("文件保存失败:"+ e);
        }

        AnYuanServer.request(data);

        return new R<>("提交成功");
    }

    @RequestMapping(value = "/message/add", method = {RequestMethod.POST})
    @Transactional
    public R<AlarmMessage> addMessage(@RequestHeader String authorization,
                                      @RequestParam Integer alarmId,
                                      @RequestParam(required = false) String content,
                                      @RequestParam(required = false) List<MultipartFile> files) {  //参数名需与前端文件标签名一样
        MobileApp mobileApp = mobileAppService.checkLogin(authorization);

        Alarm alarm = alarmDao.findById(alarmId).orElse(null);
        if (alarm == null) throw new RE("该警报不存在");
        List<String> paths = new ArrayList<>();
        AlarmMessage alarmMessage = new AlarmMessage().setAlarm(alarm).setMobileApp(mobileApp).setContent(content);
        alarmMessageDao.save(alarmMessage);

        try {
            if(files != null) {
                int i = 0;
                for (MultipartFile file : files) {
                    i++;
                    String path = "alarm/";
                    path += alarm.getId().toString()+"/";
                    path += alarmMessage.getId()+"/";
                    path += i + "_" + file.getOriginalFilename();

                    paths.add(save.toPath(file, path));
                }
            }
            alarmMessage.setPaths(paths);
            alarmMessageDao.save(alarmMessage);
        }catch (Exception e){
            alarmMessageDao.delete(alarmMessage);
            throw new RE("文件保存失败:"+ e);

        }


        return new R<AlarmMessage>("添加成功").setData(alarmMessage);
    }

    @RequestMapping(value = "/message/del", method = {RequestMethod.GET, RequestMethod.POST})
    public R<String> delMessage(@RequestHeader String authorization, @RequestBody Map<String, Object> map) throws IOException {  //参数名需与前端文件标签名一样
        Integer id = (Integer) map.get("id");

        MobileApp mobileApp = mobileAppService.checkLogin(authorization);
        AlarmMessage alarmMessage = alarmMessageDao.findById(id).orElse(null);
        if (alarmMessage == null) return new R<>("删除成功");
        if (!alarmMessage.getMobileApp().equals(mobileApp)) throw new RE("你没有权限");

        alarmMessageDao.delete(alarmMessage);
        return new R<>("删除成功");
    }

    @RequestMapping(value = "/message/all", method = {RequestMethod.GET, RequestMethod.POST})
    public R<List<AlarmMessage>> allMessage(@RequestHeader String authorization, @RequestBody Map<String, Object> map) {  //参数名需与前端文件标签名一样
        Integer id = (Integer) map.get("id");
        List<AlarmMessage> all = alarmMessageDao.findAlarmMessagesByAlarm_Id(id);
        all.sort((var1,var2)->Long.compare(var2.getCreatedAt().getTime(),var1.getCreatedAt().getTime()));
        return new R<List<AlarmMessage>>("查询成功").setData(all);
    }


}
